package com.example.pda_scanner_flutter_plugin;

import androidx.annotation.NonNull;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** PdaScannerFlutterPlugin */
public class PdaScannerFlutterPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private Context applicationContext = null;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    applicationContext = flutterPluginBinding.getApplicationContext();
    //channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), Constants.CHARGING_CHANNEL);
    //channel.setMethodCallHandler(this);
    new EventChannel(flutterPluginBinding.getBinaryMessenger(), Constants.CHARGING_CHANNEL).setStreamHandler(new EventChannel.StreamHandler() {
      private BroadcastReceiver broadcastReceiver = null;
      @Override
      public void onListen(Object arguments, EventChannel.EventSink events) {
        broadcastReceiver = new BroadcastReceiver(){
          @Override
          public void onReceive(Context context, Intent intent) {
            // 发送数据给Flutter端
            if (intent.getAction().equals(Constants.IDATA_SCAN_ACTION)) {
              events.success(intent.getStringExtra("value"));
            }else if (intent.getAction().equals(Constants.YBX_SCAN_ACTION)) {
              events.success(intent.getStringExtra("barcode_string"));
            }
          }
        };
        // 注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.IDATA_SCAN_ACTION);
        intentFilter.addAction(Constants.YBX_SCAN_ACTION);
        applicationContext.registerReceiver(broadcastReceiver,intentFilter);
      }

      @Override
      public void onCancel(Object arguments) {
        // 取消注册广播接收器
        applicationContext.unregisterReceiver(broadcastReceiver);
        broadcastReceiver = null;
      }
    });
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {

  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {

  }
}
